(function() {
    'use strict';

    /**
     * 创建weApp 控制器
     */
    angular.module('weApp.controllers', [])

            /**
             *
             * 线路站点查询(首页面)
             * tab-dash.html
             *
             */
            .controller('DashCtrl', ['$scope', '$rootScope', '$http', '$timeout', '$state', 'localStorageService', '$ionicModal', '$ionicPopup', 'showLinePageService', 'myFavorsService', 'weAppDataBase', '$compile',
                function($scope, $rootScope, $http, $timeout, $state, localStorageService, $ionicModal, $ionicPopup, showLinePageService, myFavorsService, weAppDataBase, $compile) {
                    $rootScope.appReadyPromise.promise.then(function(res) {
                        if (res == "finished") {
                            //获取附近站点URL配置
                            var nearbyUrl = $rootScope.rootLocation + "/line/station/nearby";
                            //获取线路站点更新
                            var stationUpdateUrl = $rootScope.rootLocation + "/line/station/update";
                            //获取附近站点参数配置
                            var req = {
                                method: 'post',
                                url: nearbyUrl,
                                data: {
                                    "longitude": $rootScope.userLocation.longitude,
                                    "latitude": $rootScope.userLocation.latitude,
                                    "cityCode": $rootScope.cityCode,
                                    "cityName": $rootScope.cityName
                                }
                            };

                            //系统默认城市
                            $scope.systemNormalCity = $rootScope.cityName;
                            //系统默认名称
                            $scope.sysName = $rootScope.systemName;

                            //定位城市
                            $scope.nowCity = $rootScope.userLocation.nowCity;
                            /**
                             * zhx-pop-tip 状态
                             * @type {Boolean} set true to show, set false to hide
                             */
                            $scope.tipShown = false;
                            /**
                             * Local Favors init
                             */
                            $scope.myFavors = $scope.myFavorsJSON = null;

                            //首页当前坐标周围的线路站点信息读取
                            $scope.doRefresh = function() {

                                // $http(req).then(function(result){
                                //   console.log(result);
                                // })

                                //首页当前坐标周围的线路站点信息读取
                                $http(req)
                                        .then(function(result) {

                                            /**
                                             * 附近站点原始数据
                                             * TODO 需要修改格式
                                             * @type {[type]}
                                             */
                                            $scope.lineStation = result.data.data.stations;

                                            //重构数据
                                            //这里根据上下行重构起止时间
                                            if ($scope.lineStation.length) {
                                                for (var i = 0, len = $scope.lineStation.length; i < len; i++) {
                                                    var stationLines = $scope.lineStation[i].lineStations;
                                                    if (stationLines.length) {
                                                        for (var j = 0, jLen = stationLines.length; j < jLen; j++) {
                                                            var line = stationLines[j];
                                                            //默认值为上行
                                                            line.evalStartBusTime = line.firstBusTime;
                                                            line.evalEndBusTime = line.lastBusTime;
                                                            //下行替换
                                                            if (line.lineType === 2) {
                                                                if (angular.isUndefined(line.downFirstBusTime) || angular.isUndefined(line.downLastBusTime)) {
                                                                    line.evalStartBusTime = line.firstBusTime;
                                                                    line.evalEndBusTime = line.lastBusTime;
                                                                } else {
                                                                    line.evalStartBusTime = line.downFirstBusTime.trimSpace() == "" ? line.firstBusTime : line.downFirstBusTime;
                                                                    line.evalEndBusTime = line.downLastBusTime.trimSpace() == "" ? line.lastBusTime : line.downLastBusTime;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                            /**
                                             * 是否存在用户收藏的线路
                                             * $scope.myFavors [Array] 收藏 数组 <ID>
                                             * $scope.myFavorsJSON [JSON Array] 收藏 数组 <JSON data>
                                             * 这里需要将两个属性< myFavors > < myFavorsJSON > 初始化完毕
                                             */
                                            if (localStorageService.get("myFavors") !== null && localStorageService.get("myFavorsJSON") !== null) {
                                                $scope.myFavors = JSON.parse(localStorageService.get("myFavors"));
                                                $scope.myFavorsJSON = JSON.parse(localStorageService.get("myFavorsJSON"));
                                            } else {
                                                //如果没有任何收藏数据，则直接存入浏览器空数据
                                                localStorageService.set("myFavors", null);
                                                localStorageService.set("myFavorsJSON", null);
                                            }

                                            $scope.$broadcast('scroll.refreshComplete');

                                        });

                            }

                            $scope.doRefresh();

                            /**
                             * 页面每次进入时读取一下本地收藏
                             * @param  {[type]} event [description]
                             * @param  {[type]} data  ){                      $scope.myFavors [description]
                             * @return {[type]}       [description]
                             */
                            $scope.$on("$ionicView.beforeEnter", function(event, data) {
                                $scope.myFavors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                                $scope.myFavorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));
                            });

                            /**
                             * 打开附近某个站点下面所有线路列表的页面
                             * @param  {[type]} station      [JSON Object]
                             * @param  {[type]} stationIndex [ngRepeat Index]
                             */
                            $scope.showStationLinePage = function(station, stationIndex) {
                                //循环出的第一个站点因为设计为展开状态，因此不需要使用该方法显示其下面的线路
                                if (!stationIndex)
                                    return;

                                //将当前点击的线路名称存入浏览器
                                sessionStorage.setItem("nowStationName", station.stationName);

                                /**
                                 * 点击某个站点后，通过该站点的ID将其下面所有线路的JSON数据从原始数据中过滤出来，并存入sessionStorage，供后面的子页面使用
                                 */
                                for (var i = 0; i < $scope.lineStation.length; i++) {
                                    // if( $scope.lineStation[i].stationId == station.stationId ){
                                    // 目前接收到的数据已无  $scope.lineStation[i].stationId 这个属性字段，只能用stationName来判断
                                    if ($scope.lineStation[i].stationName == station.stationName) {
                                        sessionStorage.setItem("clickStation", JSON.stringify($scope.lineStation[i].lineStations));
                                        break;
                                    }
                                }
                                //最后通过ui-router跳转页面
                                $state.go("station");

                            };

                            /**
                             * 打开线路详细页面（直线图页面）点击事件
                             * @param  {[type]} line  [线路JSON Data]
                             * @param  {[type]} event [当前点击的 event 对象]
                             */
                            $scope.showLine = function(line, event) {
                                if (angular.element(event.target).hasClass('station-favor') || angular.element(event.target).hasClass('we-font'))
                                    return;
                                showLinePageService.gotoLinePage(line, event);
                            };

                            /**
                             * 点击后将该线路加入本地收藏
                             * 收藏的数据将会被存入本地浏览器的LocalStorage中
                             * @param  {[type]} line  [line JSON Data]
                             * @param  {[type]} event [click event]
                             */
                            $scope.favorLine = function(line, event) {
                                //当前点击的lineID;
                                var stationId = line.lineStationId;
                                //如果当前myFavors数组总不含有当前点击的lineID
                                //意为当前点击的线路并未被收藏则执行收藏操作
                                if ($scope.myFavors == null)
                                    $scope.myFavors = [];
                                if ($scope.myFavors.indexOf(stationId) == -1) {
                                    //通过服务存入LocalStorage
                                    myFavorsService.set(line);
                                    //存入当前页面临时数组中
                                    $scope.myFavors.push(stationId);
                                    $scope.tipShown = true;
                                    $scope.tipContent = '收藏成功';

                                } else {    //移除操作
                                    //通过服务移除LocalStorage中的当前线路
                                    myFavorsService.remove(line);
                                    //移除临时数组中的ID
                                    $scope.myFavors.remove(stationId);
                                    $scope.tipShown = true;
                                    $scope.tipContent = '取消收藏成功';
                                }

                            }


                            //城市选择页面（modal）
                            $ionicModal.fromTemplateUrl("templates/city.html", {
                                scope: $scope,
                                animation: 'slide-in-up'
                            })
                                    //打开成功后回调
                                    .then(function(modal) {

                                        $scope.cityModal = modal;

                                        //选择城市事件
                                        $scope.selectCity = function(city) {

                                            $ionicPopup.confirm({
                                                title: "选择城市",
                                                template: "将城市切换至<strong>" + city + "</strong>？",
                                                cancelText: "取消",
                                                okText: "确定",
                                                okType: "button-balanced"
                                            }).then(function(res) {
                                                if (res) {
                                                    console.log("clear all histroy!");
                                                    $scope.cityModal.hide()
                                                } else {
                                                    console.log("clear all histroy has been canceled!");
                                                }
                                            })

                                        }

                                    });


                            //modal关闭后垃圾回收
                            $scope.$on('$destroy', function() {
                                $scope.cityModal.remove();
                            });

                        }

                    })

                }])

})();